<template>
  <view class="login-page">
    <u-form :model="form" label-width="80">
      
      <!-- 手机号 -->
      <u-form-item label="手机号" required>
        <u-input v-model.trim="form.mobile" placeholder="请输入手机号" />
      </u-form-item>

      <!-- 密码（明文） -->
      <u-form-item label="密码" required>
        <u-input
          v-model.trim="form.password"
          type="text"
          placeholder="请输入密码"
          autocomplete="off"
          autocorrect="off"
          autocapitalize="none"
          spellcheck="false"
        />
      </u-form-item>

      <view class="btn-box">
        <u-button type="primary" shape="circle" @tap="handleLogin">登录</u-button>
        <u-button
          type="default"
          shape="circle"
          customStyle="margin-top: 20rpx;"
          @tap="goRegister"
        >
          没有账号？去注册
        </u-button>
      </view>

    </u-form>
  </view>
</template>

<script>
import api from '@/api/user.js'

export default {
  data() {
    return {
      form: { mobile: '', password: '' }
    }
  },
  methods: {
    // 判断是否连续数字或连续字母
    isSequential(str) {
      if (!str) return false
      const codes = str.split('').map(c => c.charCodeAt(0))
      const isAllNum = /^[0-9]+$/.test(str)
      const isAllLetter = /^[a-zA-Z]+$/.test(str)
      if (!isAllNum && !isAllLetter) return false

      let ascending = true
      let descending = true
      for (let i = 1; i < codes.length; i++) {
        if (codes[i] !== codes[i - 1] + 1) ascending = false
        if (codes[i] !== codes[i - 1] - 1) descending = false
      }
      return ascending || descending
    },

    async handleLogin() {
      const mobileReg = /^1[3-9]\d{9}$/
      if (!mobileReg.test(this.form.mobile)) {
        uni.showToast({ title: '手机号格式不正确', icon: 'none' })
        return
      }

      if (this.form.password.length < 6) {
        uni.showToast({ title: '密码长度不能小于6位', icon: 'none' })
        return
      }

      if (this.isSequential(this.form.password)) {
        uni.showToast({ title: '密码不能是连续数字或字母', icon: 'none' })
        return
      }

      try {
        const res = await api.login(this.form)
        uni.setStorageSync('token', res.data.accessToken)
        uni.showToast({ title: '登录成功', icon: 'success' })
        setTimeout(() => uni.reLaunch({ url: '/pages/index/index' }), 800)
      } catch (err) {
        uni.showToast({ title: '请检查账号密码!', icon: 'error' })
      }
    },

    goRegister() {
      uni.navigateTo({ url: '/pages/register/index' })
    }
  }
}
</script>

<style scoped>
.login-page {
  padding: 60rpx 40rpx;
}

.btn-box {
  margin-top: 40rpx;
}

/* 背景渐变，覆盖 iOS 原生灰色背景 */
.u-input input {
  background: linear-gradient(135deg, #f9f9f9, #e6e6ff);
  border-radius: 8rpx;
  padding: 10rpx;
  color: #333;
}
</style>